package com.netcracker.ui.command;

import com.netcracker.entity.Right;
import com.netcracker.util.service.AuthorService;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.exception.DataTransmittingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AddAuthorCommand implements Command {
    private static final Logger LOGGER = LoggerFactory.getLogger(AddAuthorCommand.class);
    private final ServiceFacade serviceFacade;

    public AddAuthorCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }
    
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
         Right right = (Right) request.getSession().getAttribute("right");
        if (right!= null && right.equals(Right.ADMIN)) {
            Integer authorID = Integer.parseInt(request.getParameter("authorID"));
            AuthorService authorService = serviceFacade.getAuthorService();
            try {
                authorService.deleteAuthor(authorID);
            } catch (DataTransmittingException ex) {
                request.setAttribute("error", "Ошибка обращения к БД.");
                LOGGER.error("DB error: ", ex);
            }
        } else {
            request.setAttribute("error", "Недостаточно прав для добавления автора.");
        }
        return "?action=allAuthors";
    }
    
}